// pages/chatRobot/chatRobot.js
import api from '../../utils/api'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screenHeight: app.globalData.screenHeight, //屏幕高度
    chat_token: '',
    isIphone: false,
    is_start_chat: false,
    showLoad: false,
    showModal: false,
    showModalClass: 'hide-modal',
    scrollHeight: '100vh',
    scrollTop: "",
    recordList: [],
    commonProblemList: [
      { message: '公司的班车几点出发？'},
      { message: '公司的接驳班车下午几点出发？'},
      { message: '公司的班车在地铁站哪个位置？'},
      { message: '接驳班车上午有几趟，分别几点出发？'},
    ],
    autoHeight: true,
    textareaHeight: 50,
    is_focus: false,
    curMessae: '',
    send_btn_color: '#E5E6F3',
    inputHeight: 0,
    keyBoardDDuration: 0.25,
    lock: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.isIos()
    // this.handleStartChat()
  },
  isIos(){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform == "ios" && res.windowHeight == 667 && res.windowWidth == 375){
          that.setData({
            isIphone : true
          })
        }else{
          that.setData({
            isIphone: false
          })
        }
      }
    })
  },
  inputFocus(e) {
    // let that = this
    // let inputHeight = 0 //键盘弹起高度
    // if (e.detail.height) {
    //   inputHeight = e.detail.height
    //   if (that.data.isIphone) {
    //     if (210 < inputHeight && inputHeight < 220){ //对应机型获取键盘高度错误时
    //       inputHeight = e.detail.height + 42
    //     }
    //   }
    // }
    // that.setData({
    //   inputHeight
    // })
  },
  /**
   * 开始聊天
   */
  handleStartChat() {
    // createChatToken
    const that = this;
    if(that.data.lock) {
      return
    }
    that.setData({
      lock: true
    })
    wx.request({
      url: api.createChatToken,
      data: {},
      header: {
        'content-type': 'application/json', // 默认值
        'token': wx.getStorageSync('token')
      },
      method: "POST",
      success(res) {
        // console.log('createChatToken', res)
        if(res.data.state == 1) {
          that.setData({
            chat_token: res.data.data,
            is_start_chat: true,
            showModal: true
          })
          that.setData({
            showModalClass: 'show-modal'
          })
          setTimeout(() => {
            that.setData({
              showModalClass: 'hide-modal'
            })
          }, 3000)
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.message,
            duration: 3000
          })
        }
      },
      fail(err){
        // console.log('createChatToken err', err)
        wx.showToast({
          icon: 'none',
          title: '请求失败，请重新开始',
          duration: 3000
        })
      },
      complete() {
        that.setData({
          lock: false
        })
      }
    })
  },
  transitionEnd() {
    if(this.data.showModalClass === 'hide-modal') {
      // console.log('消失')
      this.setData({
        showModal: false,
        showLoad: false
      })
    }
  },
  keyBoardHeightChange(e) {
    let that = this
    let inputHeight = 0; //键盘弹起高度
    let keyBoardDDuration = 0.25; //键盘弹起动画时间
    let windowHeight = wx.getSystemInfoSync().windowHeight;
    if(e.detail.height) {
      inputHeight = e.detail.height
      if (that.data.isIphone) {
        if (210 < inputHeight && inputHeight < 220){ //对应机型获取键盘高度错误时
          inputHeight = e.detail.height + 42
        }
      }
      that.setData({
        scrollHeight: (windowHeight - inputHeight) + 'px'
      });
    } else {
      that.setData({
        scrollHeight: '100vh'
      });
    }
    if(e.detail.duration) {
      keyBoardDDuration = e.detail.duration
    }
    if(inputHeight !== that.data.inputHeight) {
      that.setData({
        inputHeight,
        keyBoardDDuration,
        // scrollTop: 'record_' + (this.data.recordList.length + 1)
      })
      // setTimeout(() => {
        that.setData({
          // scrollTop: this.data.recordList.length * this.data.screenHeight
          scrollTop: 'record_' + (this.data.recordList.length + 1)
        })
      // }, 250)
    }
  },
  getInput(e) {
    let send_btn_color = '';
    const { value } = e.detail;
    if(value) {
      send_btn_color = "#011566";
    } else {
      send_btn_color = '#E5E6F3';
    }
    this.setData({
      curMessae: value,
      send_btn_color
    })
  },
  handleConfirm: function(e) {
    this.setData({
      curMessae: e.detail.value,
    })
    this.sendMessage()
  },
  inputLineChange: function(e) {
    const line = e.currentTarget.dataset.line;
    if(e.detail.lineCount <= line) {
      this.setData({
        autoHeight: true
      })
    } else {
      this.setData({
        autoHeight: false
      })
    }
  },
  setRecordList(list) {
    this.setData({
      recordList: list,
      curMessae: ""
    })
    this.setData({
      // scrollTop: this.data.recordList.length * this.data.screenHeight
      scrollTop: 'record_' + (this.data.recordList.length + 1)
    })
  },
  sendMessage(e) {
    if(this.data.showLoad) {
      return 
    }
    const that = this;
    const value = e ? e.currentTarget.dataset.value : that.data.curMessae
    if(value) {
      that.setData({
        showLoad: true,
        is_focus: true,
      })
      let recordList = that.data.recordList;
      recordList.push({ type: '0', message: value, status: '0' });
      that.setRecordList(recordList)

      // recordList_me.push({ type: '3', }) 
      // that.setRecordList(recordList_me)

      wx.request({
        url: api.getAnswer,
        data: { 
          "token": that.data.chat_token,
          "content": value 
        },
        header: {
          'content-type': 'application/json', // 默认值
          'token': wx.getStorageSync('token')
        },
        method: "POST",
        success(res) {
          if (res.data.state == 1) {
            recordList[recordList.length - 1].status = '1';
            recordList.push({
              type: '1',
              message: res.data.data.replace(/^\s+|\s$/g,"")
            })
          } else if (res.data.state == 14 || res.data.state == 15 || res.data.state == 16) {
            let msg = "";
            if(res.data.state == 14) {
              msg = '每日免费体验额度已用完～'
            } else if(res.data.state == 15) {
              msg = '每日免费提问10次，您的次数已用完～'
            } else {
              msg = '含有违法违规或敏感内容，请文明提问!'
            }
            recordList[recordList.length - 1].status = '2';
            recordList.push({
              type: '4',
              message: msg
            })
          } else {
            recordList[recordList.length - 1].status = '2';
            wx.showToast({
              icon: "none",
              title: res.data.message,
              duration: 3000
            })
          }
          that.setRecordList(recordList)
        },
        fail(err){
          recordList[recordList.length - 1].status = '2';
          that.setRecordList(recordList)
          wx.showToast({
            icon: "error",
            title: "发送失败",
            duration: 3000
          })
        },
        complete() {
          that.setData({
            showLoad: false,
          })
        }
      })
    }
  },
  handleCopyText: function (e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.msg,
      success (res) {}
    })
  }
})